package com.order;


import com.Result;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.service.ExceptionHandle22;
import com.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.locks.ReentrantLock;


@RestController
@RequestMapping("/order-sentinel")
public class controller {
    @Autowired
    OrderService orderService;

    @RequestMapping("/add")
    @SentinelResource(value = "add",blockHandler = "flow")//流控處理或者異常處理
    public Result<Object> add() {
        return new Result<>("正常", 200);
    }

    public Result<Object> flow(BlockException exception) {
//        exception.printStackTrace();
        System.err.println("失败");
        return new Result<>("请不要频繁点击哦！！由于你的手速过快系统已经奔溃", 100);
    }

    @RequestMapping("/addThread")
    @SentinelResource(value = "addThread", blockHandlerClass = ExceptionHandle22.class,blockHandler = "flow")//如果没有加该注解 就可以使用异常处理的类MyBlockExceptionHandle
    public Result<Object> addThread() throws InterruptedException {
//        TimeUnit.SECONDS.sleep(5);
        return new Result<>(orderService.getOrder(), 200);
    }

    @RequestMapping("/queryOrder")
    @SentinelResource(value = "queryOrder",blockHandler = "flow")
    public Result<Object> queryOrder() {
        return new Result<>(orderService.getOrder(), 200);
    }
    @RequestMapping("/creatOrder")
    @SentinelResource(value = "creatOrder",blockHandler = "flow")
    public  Result<Object> creatOrder(){
        System.out.println("成功");

        try {
            Thread.sleep(100);
        }catch (Exception e){
            System.out.println("出错了");
        }
        ReentrantLock lock=new ReentrantLock(false);//默认非公平  两个内部类
        lock.lock();
        try {

        }finally {
            lock.unlock();
        }
        //关联流控 对queryOrder 和creatOrder 进行关联流控 如果queryOrder 流量过大 对它进行流控 让出数据库访问资源
        return new Result<>(orderService.creatOrder(), 200);
    }
}
